#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdatomic.h>

#include "task.h"
#include "unit.h"
#include "../utils/map.h"
#include "../utils/config.h"

HashMap*  loadUnitMapFromDir(const char* dir) {
    
    HashMap* map=hashmap_create(101,1024,1024,string_hash,string_compare,NULL,NULL);

    char** filepaths=listFilesPath_fromDir_multiSuffix(dir,".service|.target");
    if (filepaths==NULL) {
        printf("No service or target found.\n");
        return -1;
    }
    int i=0;
    while (filepaths[i]!=NULL) {
        char* filepath=filepaths[i];
        Unit* unit=(Unit*)malloc(sizeof(Unit));
        memset(unit,0,sizeof(Unit));
        if (unitLoadFrom(unit,filepath)<0) {
            printf("Load unit from %s failed.\n",filepath);
            continue;
        }
        TopoNode* node=malloc(sizeof(TopoNode));
        node->data=unit;
        node->indegree=0;
        node->adj=NULL;
        if (hashmap_put(map,unit->name,node)<0) {
            printf("Add unit %s to map failed.\n",unit->name);
            continue;
        }
        printf("Load unit from %s success.\n",filepath);
        i++;
    }

    return map;
}

// void parseDependency(HashMap* map,const char* in) {
//     TopoNode* node=hashmap_get(map,in);
//     Unit* unit=(Unit*)node->data;
//     char** wants=unit->wantsbyname;
//     for (size_t i = 0; wants[i]!= NULL; i++) {
//     {
//         TopoNode* child=hashmap_get(map,wants[i]);
//         if (child==NULL) {
//             printf("Unit %s wants %s, but it is not found.\n",unit->name,wants[i]);
//             continue;
//         }
//     }
 
    
// }
